<template>
  <div class="object-recognition">
    <div class="toolbar">
      <div class="left-actions">
        <ImageManager
          type="object"
          :multiple="false"
          @upload-success="handleUploadSuccess"
          @upload-error="handleUploadError"
        />
        <button class="action-btn" @click="showSettingsDialog = true">
          <i class="icon">⚙️</i>
          配置接口
        </button>
      </div>
      <div class="right-actions">
        <button class="action-btn" @click="exportDataset">
          <i class="icon">📦</i>
          导出数据集
        </button>
      </div>
    </div>

    <!-- 接口配置对话框 -->
    <div v-if="showSettingsDialog" class="dialog-overlay" @click="showSettingsDialog = false">
      <div class="settings-dialog" @click.stop>
        <h3>配置 GPU 服务器接口</h3>
        <div class="settings-tabs">
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'settings' }"
            @click="activeTab = 'settings'"
          >
            接口配置
          </button>
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'docs' }"
            @click="activeTab = 'docs'"
          >
            接口说明
          </button>
        </div>
        
        <!-- 配置表单 -->
        <div v-if="activeTab === 'settings'" class="settings-form">
          <div class="form-item">
            <label>服务器地址</label>
            <input 
              v-model="apiSettings.serverUrl" 
              placeholder="例如: http://gpu-server:5000/detect"
              type="text"
            >
            <div class="field-desc">GPU 服务器的物体检测接口地址</div>
          </div>
          <div class="form-item">
            <label>API Key (如果需要)</label>
            <input 
              v-model="apiSettings.apiKey" 
              type="password"
              placeholder="可选"
            >
            <div class="field-desc">用于接口认证的密钥，如果服务器需要的话</div>
          </div>
          <div class="form-item">
            <label>检测阈值</label>
            <input 
              v-model.number="apiSettings.threshold" 
              type="number"
              min="0"
              max="1"
              step="0.05"
            >
            <div class="field-desc">物体检测的置信度阈值，范围 0-1</div>
          </div>
          <div class="form-item">
            <label>测试连接</label>
            <button 
              class="action-btn" 
              :class="{ primary: !testingConnection }"
              @click="testConnection"
              :disabled="testingConnection"
            >
              {{ testingConnection ? '测试中...' : '测试连接' }}
            </button>
          </div>
        </div>
        
        <!-- 接口文档 -->
        <div v-else class="api-docs">
          <div class="doc-section">
            <h4>请求格式</h4>
            <pre class="code-block">
POST {your-server}/detect

Headers:
{
  'Content-Type': 'multipart/form-data',
  'X-API-Key': 'your_api_key'  // 可选
}

Body: FormData {
  file: File,            // 图片文件
  threshold: number      // 检测阈值 (0-1)
}</pre>
          </div>
          
          <div class="doc-section">
            <h4>响应格式</h4>
            <pre class="code-block">
{
  "original_image": string,    // 原始图片路径
  "annotated_image": string,   // 标注后的图片路径
  "objects": [{
    "id": number,             // 物体ID
    "category": string,       // 物体类别
    "confidence": number,     // 置信度 (0-1)
    "bbox": {                 // 边界框（百分比坐标）
      "x": number,           // 左上角x坐标
      "y": number,           // 左上角y坐标
      "width": number,       // 宽度
      "height": number       // 高度
    }
  }]
}</pre>
          </div>
          
          <div class="doc-section">
            <h4>错误响应</h4>
            <pre class="code-block">
{
  "detail": string  // 错误信息
}</pre>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="action-btn" @click="showSettingsDialog = false">取消</button>
          <button class="action-btn primary" @click="saveSettings">保存</button>
        </div>
      </div>
    </div>

    <div class="content-area">
      <!-- 左侧缩略图列表 -->
      <div class="thumbnails-list">
        <div v-for="image in images" 
             :key="image.id" 
             class="image-item"
             :class="{ active: currentImage?.id === image.id }"
             @click="selectImage(image)">
          <div class="thumbnail">
            <img :src="`http://111.229.88.2:8000/uploads/${image.filename}`" 
                 :alt="image.filename"
                 @error="handleImageError">
          </div>
          <div class="image-info">
            <span class="filename">{{ getFileName(image.filename) }}</span>
            <span class="object-count" v-if="image.objects">
              {{ image.objects.length }} 个物体
            </span>
          </div>
          <div class="image-actions">
            <button class="delete-btn" @click.stop="confirmDelete(image)">
              <i class="icon">🗑️</i>
            </button>
          </div>
        </div>
      </div>

      <!-- 中间和右侧的图片显示区域 -->
      <div class="main-content" v-if="currentImage">
        <!-- 原图 -->
        <div class="image-container original">
          <h3>原始图片</h3>
          <img :src="`http://111.229.88.2:8000/uploads/${currentImage.filename}`" 
               :alt="currentImage.filename"
               @error="handleImageError">
        </div>

        <!-- 标注图 -->
        <div class="image-container annotated" v-if="currentImage.annotated_image">
          <h3>物体检测结果</h3>
          <div class="image-wrapper">
            <img :src="`http://111.229.88.2:8000/uploads/${currentImage.annotated_image}`" 
                 :alt="currentImage.filename"
                 @error="handleImageError">
            <div v-for="object in objects" 
                 :key="object.id" 
                 class="object-box"
                 :style="getObjectStyle(object)"
                 @click="selectObject(object)">
              <div class="object-label">
                {{ object.category }} ({{ (object.confidence * 100).toFixed(0) }}%)
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧结果显示区域 -->
      <div class="result-area">
        <div v-if="!currentImage" class="placeholder">
          请上传图片进行物体检测
        </div>
        <div v-else-if="loading" class="placeholder">
          正在处理图片...
        </div>
        <div v-else>
          <h3>检测结果</h3>
          <div class="category-summary">
            <h4>检测到的物体数量：{{ objects.length }}</h4>
          </div>
          <div class="object-list">
            <div v-for="object in objects" 
                 :key="object.id" 
                 class="object-item"
                 :class="{ active: selectedObject?.id === object.id }"
                 @click="selectObject(object)">
              <div class="object-header">
                <span>{{ object.category }}</span>
                <span class="confidence">置信度: {{ (object.confidence * 100).toFixed(1) }}%</span>
              </div>
              <div class="object-details">
                <p>位置: ({{ object.bbox.x.toFixed(1) }}%, {{ object.bbox.y.toFixed(1) }}%)</p>
                <p>大小: {{ object.bbox.width.toFixed(1) }}% x {{ object.bbox.height.toFixed(1) }}%</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import ImageManager from './ImageManager.vue'

const images = ref([])
const currentImage = ref(null)
const selectedObject = ref(null)
const objects = ref([])
const loading = ref(false)
const showSettingsDialog = ref(false)
const activeTab = ref('settings')
const testingConnection = ref(false)

// API 设置
const apiSettings = ref({
  serverUrl: localStorage.getItem('objectDetectionUrl') || 'http://localhost:5000/detect',
  apiKey: localStorage.getItem('objectDetectionKey') || '',
  threshold: parseFloat(localStorage.getItem('objectDetectionThreshold')) || 0.5
})

// 保存设置
const saveSettings = () => {
  localStorage.setItem('objectDetectionUrl', apiSettings.value.serverUrl)
  localStorage.setItem('objectDetectionKey', apiSettings.value.apiKey)
  localStorage.setItem('objectDetectionThreshold', apiSettings.value.threshold)
  showSettingsDialog.value = false
}

// 处理上传成功
const handleUploadSuccess = (data) => {
  const imageData = {
    id: Date.now(),
    filename: data.original_image,
    annotated_image: data.annotated_image,
    objects: data.objects || []
  }
  images.value.unshift(imageData)
  currentImage.value = imageData
  objects.value = imageData.objects
}

// 处理上传失败
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  alert('上传失败: ' + error)
}

// 选择图片
const selectImage = (image) => {
  currentImage.value = image
  objects.value = image.objects || []
  selectedObject.value = null
}

// 选择物体
const selectObject = (object) => {
  selectedObject.value = object
}

// 获取物体框样式
const getObjectStyle = (object) => {
  if (!object.bbox) return {}
  
  return {
    left: `${object.bbox.x}%`,
    top: `${object.bbox.y}%`,
    width: `${object.bbox.width}%`,
    height: `${object.bbox.height}%`,
    border: selectedObject.value?.id === object.id ? '2px solid #ff4d4f' : '2px solid #52c41a'
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = ''
}

// 获取文件名
const getFileName = (filename) => {
  return filename.split('/').pop()
}

// 确认删除
const confirmDelete = async (image) => {
  if (!confirm('确定要删除这张图片吗？')) return
  
  try {
    await axios.delete(`http://111.229.88.2:8000/api/images/${image.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    images.value = images.value.filter(img => img.id !== image.id)
    if (currentImage.value?.id === image.id) {
      currentImage.value = null
      objects.value = []
    }
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 导出数据集
const exportDataset = async () => {
  try {
    const response = await axios.get('http://111.229.88.2:8000/api/export', {
      params: { type: 'object' },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      responseType: 'blob'
    })
    
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `object_dataset_${new Date().getTime()}.zip`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 测试连接
const testConnection = async () => {
  if (!apiSettings.value.serverUrl) {
    alert('请先填写服务器地址')
    return
  }
  
  testingConnection.value = true
  try {
    const response = await axios.get(`${apiSettings.value.serverUrl}/status`, {
      headers: apiSettings.value.apiKey ? {
        'X-API-Key': apiSettings.value.apiKey
      } : undefined,
      timeout: 5000
    })
    
    if (response.data?.status === 'ok') {
      alert('连接成功！服务器运行正常。')
    } else {
      alert('连接成功，但服务器状态异常。')
    }
  } catch (error) {
    console.error('测试连接失败:', error)
    alert(`连接失败: ${error.response?.data?.detail || error.message}`)
  } finally {
    testingConnection.value = false
  }
}

// 加载图片列表
onMounted(async () => {
  try {
    const response = await axios.get('http://111.229.88.2:8000/api/images', {
      params: { type: 'object' },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    images.value = response.data
  } catch (error) {
    console.error('加载图片列表失败:', error)
  }
})
</script>

<style scoped>
.object-recognition {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.action-btn:hover {
  background-color: #e0e0e0;
}

.action-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.5;
}

.action-btn.primary {
  background-color: #52c41a;
  color: white;
}

.action-btn.primary:hover {
  background-color: #389e0d;
}

.icon {
  font-size: 16px;
  line-height: 1;
}

.content-area {
  flex: 1;
  display: grid;
  grid-template-columns: 200px 1fr 300px;
  gap: 20px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.thumbnails-list {
  padding: 20px;
  overflow: auto;
  border-right: 1px solid #e8e8e8;
  background: #f8f8f8;
}

.image-item {
  position: relative;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-item.active {
  border: 2px solid #52c41a;
}

.thumbnail {
  width: 100%;
  height: 120px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 8px;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-info {
  display: flex;
  flex-direction: column;
}

.filename {
  font-size: 14px;
  color: #333;
}

.object-count {
  font-size: 12px;
  color: #999;
}

.image-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

.delete-btn {
  padding: 4px;
  background: rgba(255, 59, 48, 0.9);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.delete-btn:hover {
  background: rgba(255, 59, 48, 1);
  transform: scale(1.1);
}

.main-content {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px;
  background: white;
}

.image-container {
  position: relative;
  background: #f8f8f8;
  border-radius: 8px;
  padding: 16px;
}

.image-container h3 {
  margin: 0 0 16px 0;
  color: #52c41a;
  font-size: 16px;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 12px;
}

.image-container img {
  max-width: 100%;
  height: auto;
}

.original {
  padding: 20px;
  overflow: auto;
}

.annotated {
  padding: 20px;
  overflow: auto;
}

.image-wrapper {
  position: relative;
}

.object-box {
  position: absolute;
  border: 2px solid #52c41a;
  cursor: pointer;
  transition: all 0.3s;
}

.object-box:hover {
  border-color: #ff4d4f;
}

.object-label {
  position: absolute;
  top: -25px;
  left: 0;
  background: rgba(82, 196, 26, 0.9);
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
  white-space: nowrap;
}

.confidence {
  color: #52c41a;
}

.result-area {
  padding: 20px;
  background: #f8f8f8;
  border-left: 1px solid #e8e8e8;
}

.placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.category-summary {
  margin-bottom: 24px;
  background: white;
  padding: 16px;
  border-radius: 8px;
}

.category-summary h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.object-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.object-item {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.object-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.confidence {
  color: #52c41a;
  font-size: 14px;
}

.object-details p {
  margin: 8px 0;
  color: #666;
}

.settings-dialog {
  background-color: white;
  padding: 24px;
  border-radius: 8px;
  width: 600px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
}

.settings-dialog h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.settings-tabs {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 12px;
}

.tab-btn {
  padding: 8px 16px;
  border: none;
  background: none;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.tab-btn:hover {
  color: #52c41a;
  background: #f6ffed;
}

.tab-btn.active {
  color: #52c41a;
  background: #f6ffed;
  font-weight: 500;
}

.settings-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.field-desc {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.api-docs {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.doc-section h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.code-block {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 13px;
  white-space: pre;
  overflow-x: auto;
}
</style> 